package edu.sias.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DButil {
	/**
	* 设置URL，建立连接时，指向数据库的地址
	 */
	private static String url="jdbc:mysql://localhost:3306/sias";
	/**
	 *设置变量，和用户建立连接
	 */
	private static String user="root";
	private static String password="root";
	private static Connection connection;
	private static PreparedStatement ps;
	private static ResultSet rs;
	
	/**
	 * 1加载驱动 calss.forname("com,mysql.jdbc.Driver")
	 */
	public static  Connection  getConnection(){
		try {
			Class.forName("com.mysql.jdbc.Driver");
			System.out.println("加载成功");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			System.out.println("加载失败");
			e.printStackTrace();
		}
		
		try {
			connection=DriverManager.getConnection(url, user, password);
			System.out.println("连接成功");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("连接失败");
			e.printStackTrace();
		}
		return connection;
		
	}
	
	
	/**
	 * 6.关闭资源
	 * @throws SQLException 
	 */
	public static void close() throws SQLException{
		if(rs!=null){
			rs.close();
		}
		
		if(ps!=null){
			ps.close();
		}
		
		if(connection!=null){
			connection.close();
		}
	}

	
	
	
	/**
	 * 查询
	 * @param sql  sql  selct * from emp where e_age=? and e_name=?
	 * @param obj  object[]
	 * @return    结果集
	 */
	public static ResultSet select(String sql,Object[]obj){
		// 1获取链接
		connection=getConnection();
		//预处理sql
		try {
			ps=connection.prepareStatement(sql);
			//执行sql
			for(int i=0;i<obj.length;i++){
				ps.setObject(i+1, obj[i]);
			}
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//4ִ 执行
		try {
			rs=ps.executeQuery();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return rs;
		
	}
	
	
	/**
	 * 增删改
	 * @param sql
	 * @param obj
	 * @return    
	 */
	public static int update(String sql,Object[]obj){
		//1 获取链接
		connection =getConnection();
		//预处理sql
		try {
			ps=connection.prepareStatement(sql);
			//参数添加
			for(int i=0;i<obj.length;i++){
				ps.setObject(i+1, obj[i]);
			}
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//4.ִ执行
		int a=0;
		try {
			 a=ps.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return a;
	}

}
